package com.aclyyx.mi.display.remote.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.Socket;
import java.util.TimerTask;

import android.util.Log;
import android.widget.Toast;

import com.aclyyx.mi.display.MiActivity;
import com.aclyyx.mi.display.Param;
import com.aclyyx.mi.display.R;

public class CompareTask extends TimerTask {
	
	private Param param;
	private MiActivity a;
	
	public CompareTask(MiActivity a, Param param) {
		this.a = a;
		this.param = param;
	}

	@Override
	public void run() {
		Socket s = null;
		BufferedReader in = null;
		try {
			s = new Socket(param.ip, Integer.parseInt(param.port));
			in = new BufferedReader(new InputStreamReader(s.getInputStream()), 100);
			
			String line = null;
			a.setTime(System.currentTimeMillis());
			try {
				line = in.readLine();
			} catch (Exception e) {
				return;
			}
			param.runtime = Long.valueOf(line);
			
		} catch (ConnectException e) {
			a.runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(a, R.string.msg_server_is_closed, Toast.LENGTH_SHORT).show();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (IOException e) {
			}
			try {
				if (s != null) {
					s.close();
					s = null;
				}
			} catch (IOException e) {
			}
		}
	}
}
